package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.SocialUser;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.common.vo.MemberVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理社交登录请求
 */
@Controller
@Slf4j
public class OAuth2Controller {

    @Autowired
    private MemberFeignService memberFeignService;

    /**
     * 微博登录
     * @param code
     * @return
     * @throws Exception
     */
    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession httpSession) throws Exception {
        Map<String, String> headers = new HashMap<>();
        Map<String, String> querys = new HashMap<>();
        Map<String, String> bodys = new HashMap<>();
        bodys.put("client_id", "3227987808");
        bodys.put("client_secret", "70631a35ad0bada7c61dadc600204b5f");
        bodys.put("grant_type", "authorization_code");
        bodys.put("redirect_uri", "http://auth.gulimall.com/oauth2.0/weibo/success");
        bodys.put("code", code);
        // 1、根据code换取accessToken
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", headers, querys, bodys);
        // 2、处理响应内容
        if (response.getStatusLine().getStatusCode() == 200) {
            // 获取到了accessToken
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
            // 判断当前社交用户是否是谷粒商城新用户，若为新用户，自动为该社交账号生成一个谷粒商城系统的会员信息账号，并与其社交账号关联
            try {
                R result = memberFeignService.weiboLogin(socialUser);
                if (result.getCode() == 0) {
                    MemberVo member = result.getData("data", new TypeReference<MemberVo>(){});
                    log.info("登录成功，登录用户为：{}", member);
                    // 将session信息存到redis中
                    httpSession.setAttribute(AuthServerConstant.LOGIN_USER, member);
                }
            } catch (Exception e) {
                return "redirect:http://auth.gulimall.com/login.html";
            }
        } else {
            // 未获取到accessToken，登录失败，返回到登录页
            return "redirect:http://auth.gulimall.com/login.html";
        }
        // 2、登录成功就跳回首页
        return "redirect:http://gulimall.com";
    }
}
